﻿#region zh-CHS 2006 - 2007 DemoSoft 团队 | en 2006 - 2007 DemoSoft Team

//     NOTES
// ---------------
//
// This file is a part of the G.O.S.E(Game Online Server Engine) for .NET.
//
//                 2006-2007 DemoSoft Team
//
//
// First Version : by H.Q.Cai - mailto:caihuanqing@hotmail.com

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as published
 *   by the Free Software Foundation; either version 2.1 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

#region zh-CHS 包含名字空间 | en Include namespace
using System;
using System.IO;
using System.Net;
using System.Xml;
using System.Text;
using Microsoft.Win32;
using System.Reflection;
using System.Collections;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Demo_G.O.S.E.ServerEngine.Common;
#endregion

namespace Demo_G.O.S.E.ServerEngine.Util
{
    #region zh-CHS 类 | en Class
    /// <summary>
    /// 
    /// </summary>
    public sealed class ServerInfo
    {
        #region zh-CHS 私有成员变量 | en Private Member Variables
        /// <summary>
        /// 
        /// </summary>
        private string m_ServerName;
        /// <summary>
        /// 
        /// </summary>
        private long m_ServerGuid;
        /// <summary>
        /// 
        /// </summary>
        private long m_FullPercent;
        /// <summary>
        /// 
        /// </summary>
        private long m_TimeZone;
        /// <summary>
        /// 
        /// </summary>
        private IPEndPoint m_Address;
        #endregion

        #region zh-CHS 构造和初始化和清理 | en Constructors and Initializers and Dispose
        /// <summary>
        /// 
        /// </summary>
        /// <param name="strName"></param>
        /// <param name="iGuid"></param>
        /// <param name="iFullPercent"></param>
        /// <param name="timeZone"></param>
        /// <param name="address"></param>
        public ServerInfo( string strName, long iGuid, long iFullPercent, TimeZone timeZone, IPEndPoint address )
        {
            m_ServerName = strName;
            m_ServerGuid = iGuid;
            m_FullPercent = iFullPercent;
            m_TimeZone = timeZone.GetUtcOffset( DateTime.Now ).Hours;
            m_Address = address;
        }
        #endregion

        #region zh-CHS 属性 | en Properties
        /// <summary>
        /// 
        /// </summary>
        public string ServerName
        {
            get { return m_ServerName; }
            set { m_ServerName = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        public long ServerGuid
        {
            get { return m_ServerGuid; }
            set { m_ServerGuid = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        public long FullPercent
        {
            get { return m_FullPercent; }
            set { m_FullPercent = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        public long TimeZone
        {
            get { return m_TimeZone; }
            set { m_TimeZone = value; }
        }

        /// <summary>
        /// 
        /// </summary>
        public IPEndPoint Address
        {
            get { return m_Address; }
            set { m_Address = value; }
        }
        #endregion
    }
    #endregion

    #region Convert FLOAT UINT INT
    /// <summary>
    /// 
    /// </summary>
    [StructLayout( LayoutKind.Explicit, Size = 8 )]
    public struct CONVERT_FLOAT_INT_UINT
    {
        /// <summary>
        /// 
        /// </summary>
        [FieldOffset( 0 )]
        public uint uiUint;

        /// <summary>
        /// 
        /// </summary>
        [FieldOffset( 0 )]
        public int iInt;

        /// <summary>
        /// 
        /// </summary>
        [FieldOffset( 0 )]
        public float fFloat;
    }
    #endregion

    public static class Utility
    {
        /// <summary>
        /// 
        /// </summary>
        private static Random s_Random              = new Random();


        /// <summary>
        /// 
        /// </summary>
        private static Encoding s_UTF8              = new UTF8Encoding( false, false );
        /// <summary>
        /// 
        /// </summary>
        public static Encoding UTF8
        {
            get { return s_UTF8; }
        }

        /// <summary>
        /// 
        /// </summary>
        private static Encoding s_UTF8WithEncoding  = new UTF8Encoding( true, false );
        /// <summary>
        /// 
        /// </summary>
        public static Encoding UTF8WithEncoding
        {
            get { return s_UTF8WithEncoding; }
        }

        /// <summary>
        /// 合并字符串
        /// </summary>
        /// <param name="sb"></param>
        /// <param name="value"></param>
        /// <param name="separator"></param>
        public static void Separate( ref StringBuilder stringBuilder, string strValue, string strSeparator )
        {
            if ( stringBuilder.Length > 0 )
                stringBuilder.Append( strSeparator );

            stringBuilder.Append( strValue );
        }

//        public static string Intern(string str)
//        {
//            if (str == null)
//                return null;
//            else if (str.Length == 0)
//                return String.Empty;

//            return String.Intern(str);
//        }

//        public static void Intern(ref string str)
//        {
//            str = Intern(str);
//        }

//        public static bool IsValidIP(string text)
//        {
//            bool valid = true;

//            IPMatch(text, IPAddress.None, ref valid);

//            return valid;
//        }

//        public static bool IPMatch(string val, IPAddress ip)
//        {
//            bool valid = true;

//            return IPMatch(val, ip, ref valid);
//        }

//        public static string FixHtml(string str)
//        {
//            if (str == null)
//                return "";

//            bool hasOpen = (str.IndexOf('<') >= 0);
//            bool hasClose = (str.IndexOf('>') >= 0);
//            bool hasPound = (str.IndexOf('#') >= 0);

//            if (!hasOpen && !hasClose && !hasPound)
//                return str;

//            StringBuilder sb = new StringBuilder(str);

//            if (hasOpen)
//                sb.Replace('<', '(');

//            if (hasClose)
//                sb.Replace('>', ')');

//            if (hasPound)
//                sb.Replace('#', '-');

//            return sb.ToString();
//        }

//        public static bool IPMatchCIDR(string cidr, IPAddress ip)
//        {
//            string[] str = cidr.Split('/');

//            if (str.Length < 2)
//                return false;

//            IPAddress cidrPrefix;

//            if (!IPAddress.TryParse(str[0], out cidrPrefix))
//                return false;

//            int cidrLength = Utility.ToInt32(str[1]);

//            return IPMatchCIDR(cidrPrefix, ip, cidrLength);
//        }

//        public static bool IPMatchCIDR(IPAddress cidrPrefix, IPAddress ip, int cidrLength)
//        {
//            if (cidrPrefix == null || ip == null)
//                return false;

//            if (cidrLength <= 0 || cidrLength >= 32)   //if invalid cidr Length, just compare IPs
//                return ip.Equals(cidrPrefix);

//            uint mask = uint.MaxValue << cidrLength;

//            long cidrValue = Utility.GetLongAddressValue(cidrPrefix);
//            long ipValue = Utility.GetLongAddressValue(ip);

//            return ((cidrValue & mask) == (ipValue & mask));
//        }

//        public static bool IPMatch(string val, IPAddress ip, ref bool valid)
//        {
//            valid = true;

//            string[] split = val.Split('.');

//            for (int i = 0; i < 4; ++i)
//            {
//                int lowPart, highPart;

//                if (i >= split.Length)
//                {
//                    lowPart = 0;
//                    highPart = 255;
//                }
//                else
//                {
//                    string pattern = split[i];

//                    if (pattern == "*")
//                    {
//                        lowPart = 0;
//                        highPart = 255;
//                    }
//                    else
//                    {
//                        lowPart = 0;
//                        highPart = 0;

//                        bool highOnly = false;
//                        int lowBase = 10;
//                        int highBase = 10;

//                        for (int j = 0; j < pattern.Length; ++j)
//                        {
//                            char c = (char)pattern[j];

//                            if (c == '?')
//                            {
//                                if (!highOnly)
//                                {
//                                    lowPart *= lowBase;
//                                    lowPart += 0;
//                                }

//                                highPart *= highBase;
//                                highPart += highBase - 1;
//                            }
//                            else if (c == '-')
//                            {
//                                highOnly = true;
//                                highPart = 0;
//                            }
//                            else if (c == 'x' || c == 'X')
//                            {
//                                lowBase = 16;
//                                highBase = 16;
//                            }
//                            else if (c >= '0' && c <= '9')
//                            {
//                                int offset = c - '0';

//                                if (!highOnly)
//                                {
//                                    lowPart *= lowBase;
//                                    lowPart += offset;
//                                }

//                                highPart *= highBase;
//                                highPart += offset;
//                            }
//                            else if (c >= 'a' && c <= 'f')
//                            {
//                                int offset = 10 + (c - 'a');

//                                if (!highOnly)
//                                {
//                                    lowPart *= lowBase;
//                                    lowPart += offset;
//                                }

//                                highPart *= highBase;
//                                highPart += offset;
//                            }
//                            else if (c >= 'A' && c <= 'F')
//                            {
//                                int offset = 10 + (c - 'A');

//                                if (!highOnly)
//                                {
//                                    lowPart *= lowBase;
//                                    lowPart += offset;
//                                }

//                                highPart *= highBase;
//                                highPart += offset;
//                            }
//                            else
//                            {
//                                valid = false;
//                            }
//                        }
//                    }
//                }

//                int b = (byte)(Utility.GetAddressValue(ip) >> (i * 8));

//                if (b < lowPart || b > highPart)
//                    return false;
//            }

//            return true;
//        }

//        public static bool IPMatchClassC(IPAddress ip1, IPAddress ip2)
//        {
//            return ((Utility.GetAddressValue(ip1) & 0xFFFFFF) == (Utility.GetAddressValue(ip2) & 0xFFFFFF));
//        }

//        public static int InsensitiveCompare(string first, string second)
//        {
//            return Insensitive.Compare(first, second);
//        }

//        public static bool InsensitiveStartsWith(string first, string second)
//        {
//            return Insensitive.StartsWith(first, second);
//        }

        #region To[Something]
        public static bool ToBoolean( string strValue )
        {
            bool l_bReturn;
            bool.TryParse( strValue, out l_bReturn );

            return l_bReturn;
        }

        public static double ToDouble( string strValue )
        {
            double l_dReturn;
            double.TryParse( strValue, out l_dReturn );

            return l_dReturn;
        }

        public static TimeSpan ToTimeSpan( string strValue )
        {
            TimeSpan l_tReturn;
            TimeSpan.TryParse( strValue, out l_tReturn );

            return l_tReturn;
        }

        public static int ToInt32( string strValue )
        {
            int l_iReturn;
            if ( strValue.StartsWith( "0x" ) )
                int.TryParse( strValue.Substring( 2 ), NumberStyles.HexNumber, null, out l_iReturn );
            else
                int.TryParse( strValue, out l_iReturn );

            return l_iReturn;
        }
        #endregion

        #region Get[Something]
        public static int GetInt32( string intString, int defaultValue )
        {
            try
            {
                return XmlConvert.ToInt32( intString );
            }
            catch
            {
                try
                {
                    return Convert.ToInt32( intString );
                }
                catch
                {
                    return defaultValue;
                }
            }
        }

        public static DateTime GetDateTime( string dateTimeString, DateTime defaultValue )
        {
            try
            {
                return XmlConvert.ToDateTime( dateTimeString, XmlDateTimeSerializationMode.Local );
            }
            catch
            {
                DateTime l_dReturn;

                if ( DateTime.TryParse( dateTimeString, out l_dReturn ) )
                    return l_dReturn;

                return defaultValue;
            }
        }

        public static TimeSpan GetTimeSpan( string timeSpanString, TimeSpan defaultValue )
        {
            try
            {
                return XmlConvert.ToTimeSpan( timeSpanString );
            }
            catch
            {
                return defaultValue;
            }
        }

        public static string GetAttribute( XmlElement nodeXmlElement, string strAttributeName )
        {
            return GetAttribute( nodeXmlElement, strAttributeName, null );
        }

        public static string GetAttribute( XmlElement nodeXmlElement, string strAttributeName, string strDefaultValue )
        {
            if ( nodeXmlElement == null )
                return strDefaultValue;

            XmlAttribute xmlAttribute = nodeXmlElement.Attributes[strAttributeName];

            if ( xmlAttribute == null )
                return strDefaultValue;

            return xmlAttribute.Value;
        }

        public static string GetText( XmlElement nodeXmlElement, string strDefaultValue )
        {
            if ( nodeXmlElement == null )
                return strDefaultValue;

            return nodeXmlElement.InnerText;
        }

        public static int GetAddressValue( IPAddress address )
        {
#pragma warning disable 618
            return (int)address.Address;
#pragma warning restore 618
        }

        public static long GetLongAddressValue( IPAddress address )
        {
#pragma warning disable 618
            return address.Address;
#pragma warning restore 618
        }
        #endregion

        //#region In[...]Range
        //public static bool InRange( Point3D p1, Point3D p2, int range )
        //{
        //    return ( p1.m_X >= ( p2.m_X - range ) )
        //        && ( p1.m_X <= ( p2.m_X + range ) )
        //        && ( p1.m_Y >= ( p2.m_Y - range ) )
        //        && ( p1.m_Y <= ( p2.m_Y + range ) );
        //}

        //public static bool InUpdateRange( Point3D p1, Point3D p2 )
        //{
        //    return ( p1.m_X >= ( p2.m_X - 18 ) )
        //        && ( p1.m_X <= ( p2.m_X + 18 ) )
        //        && ( p1.m_Y >= ( p2.m_Y - 18 ) )
        //        && ( p1.m_Y <= ( p2.m_Y + 18 ) );
        //}

        //public static bool InUpdateRange( Point2D p1, Point2D p2 )
        //{
        //    return ( p1.m_X >= ( p2.m_X - 18 ) )
        //        && ( p1.m_X <= ( p2.m_X + 18 ) )
        //        && ( p1.m_Y >= ( p2.m_Y - 18 ) )
        //        && ( p1.m_Y <= ( p2.m_Y + 18 ) );
        //}

        //public static bool InUpdateRange( IPoint2D p1, IPoint2D p2 )
        //{
        //    return ( p1.X >= ( p2.X - 18 ) )
        //        && ( p1.X <= ( p2.X + 18 ) )
        //        && ( p1.Y >= ( p2.Y - 18 ) )
        //        && ( p1.Y <= ( p2.Y + 18 ) );
        //}
        //#endregion

//        public static Direction GetDirection(IPoint2D from, IPoint2D to)
//        {
//            int dx = to.X - from.X;
//            int dy = to.Y - from.Y;

//            int adx = Math.Abs(dx);
//            int ady = Math.Abs(dy);

//            if (adx >= ady * 3)
//            {
//                if (dx > 0)
//                    return Direction.East;
//                else
//                    return Direction.West;
//            }
//            else if (ady >= adx * 3)
//            {
//                if (dy > 0)
//                    return Direction.South;
//                else
//                    return Direction.North;
//            }
//            else if (dx > 0)
//            {
//                if (dy > 0)
//                    return Direction.Down;
//                else
//                    return Direction.Right;
//            }
//            else
//            {
//                if (dy > 0)
//                    return Direction.Left;
//                else
//                    return Direction.Up;
//            }
//        }

//        public static bool CanMobileFit(int z, Tile[] tiles)
//        {
//            int checkHeight = 15;
//            int checkZ = z;

//            for (int i = 0; i < tiles.Length; ++i)
//            {
//                Tile tile = tiles[i];

//                if (((checkZ + checkHeight) > tile.Z && checkZ < (tile.Z + tile.Height))/* || (tile.Z < (checkZ + checkHeight) && (tile.Z + tile.Height) > checkZ)*/ )
//                {
//                    return false;
//                }
//                else if (checkHeight == 0 && tile.Height == 0 && checkZ == tile.Z)
//                {
//                    return false;
//                }
//            }

//            return true;
//        }

//        public static bool IsInContact(Tile check, Tile[] tiles)
//        {
//            int checkHeight = check.Height;
//            int checkZ = check.Z;

//            for (int i = 0; i < tiles.Length; ++i)
//            {
//                Tile tile = tiles[i];

//                if (((checkZ + checkHeight) > tile.Z && checkZ < (tile.Z + tile.Height))/* || (tile.Z < (checkZ + checkHeight) && (tile.Z + tile.Height) > checkZ)*/ )
//                {
//                    return true;
//                }
//                else if (checkHeight == 0 && tile.Height == 0 && checkZ == tile.Z)
//                {
//                    return true;
//                }
//            }

//            return false;
//        }

//        public static object GetArrayCap(Array array, int index)
//        {
//            return GetArrayCap(array, index, null);
//        }

//        public static object GetArrayCap(Array array, int index, object emptyValue)
//        {
//            if (array.Length > 0)
//            {
//                if (index < 0)
//                {
//                    index = 0;
//                }
//                else if (index >= array.Length)
//                {
//                    index = array.Length - 1;
//                }

//                return array.GetValue(index);
//            }
//            else
//            {
//                return emptyValue;
//            }
//        }

//        //4d6+8 would be: Utility.Dice( 4, 6, 8 )
//        public static int Dice(int numDice, int numSides, int bonus)
//        {
//            int total = 0;
//            for (int i = 0; i < numDice; ++i)
//                total += Random(numSides) + 1;
//            total += bonus;
//            return total;
        //        }

        #region Random
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static double RandomDouble()
        {
            return s_Random.NextDouble();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static bool RandomBool()
        {
            return ( s_Random.Next( 2 ) == 0 );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="iCount"></param>
        /// <returns></returns>
        public static long Random( long iCount )
        {
            return s_Random.Next( (int)iCount );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="intList"></param>
        /// <returns></returns>
        public static long RandomList( params int[] intList )
        {
            return intList[s_Random.Next( intList.Length )];
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="iMin"></param>
        /// <param name="iMax"></param>
        /// <returns></returns>
        public static int RandomMinMax( int iMin, int iMax )
        {
            if ( iMin > iMax )
            {
                int iCopy = iMin;
                iMin = iMax;
                iMax = iCopy;
            }
            else if ( iMin == iMax )
                return iMin;

            return s_Random.Next( iMin, iMax );
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="iFrom"></param>
        /// <param name="iCount"></param>
        /// <returns></returns>
        public static int Random( int iFrom, int iCount )
        {
            if ( iCount == 0 )
                return iFrom;
            else if ( iCount > 0 )
                return iFrom + s_Random.Next( iCount );
            else
                return iFrom - s_Random.Next( -iCount );
        }
        #endregion

        //        #region Random Hues

//        public static int RandomNondyedHue()
//        {
//            switch (Random(6))
//            {
//                case 0: return RandomPinkHue();
//                case 1: return RandomBlueHue();
//                case 2: return RandomGreenHue();
//                case 3: return RandomOrangeHue();
//                case 4: return RandomRedHue();
//                case 5: return RandomYellowHue();
//            }

//            return 0;
//        }

//        public static int RandomPinkHue()
//        {
//            return Random(1201, 54);
//        }

//        public static int RandomBlueHue()
//        {
//            return Random(1301, 54);
//        }

//        public static int RandomGreenHue()
//        {
//            return Random(1401, 54);
//        }

//        public static int RandomOrangeHue()
//        {
//            return Random(1501, 54);
//        }

//        public static int RandomRedHue()
//        {
//            return Random(1601, 54);
//        }

//        public static int RandomYellowHue()
//        {
//            return Random(1701, 54);
//        }

//        public static int RandomNeutralHue()
//        {
//            return Random(1801, 108);
//        }

//        public static int RandomSnakeHue()
//        {
//            return Random(2001, 18);
//        }

//        public static int RandomBirdHue()
//        {
//            return Random(2101, 30);
//        }

//        public static int RandomSlimeHue()
//        {
//            return Random(2201, 24);
//        }

//        public static int RandomAnimalHue()
//        {
//            return Random(2301, 18);
//        }

//        public static int RandomMetalHue()
//        {
//            return Random(2401, 30);
//        }

//        public static int ClipDyedHue(int hue)
//        {
//            if (hue < 2)
//                return 2;
//            else if (hue > 1001)
//                return 1001;
//            else
//                return hue;
//        }

//        public static int RandomDyedHue()
//        {
//            return Random(2, 1000);
//        }

//        //[Obsolete( "Depreciated, use the methods for the Mobile's race", false )]
//        public static int ClipSkinHue(int hue)
//        {
//            if (hue < 1002)
//                return 1002;
//            else if (hue > 1058)
//                return 1058;
//            else
//                return hue;
//        }

//        //[Obsolete( "Depreciated, use the methods for the Mobile's race", false )]
//        public static int RandomSkinHue()
//        {
//            return Random(1002, 57) | 0x8000;
//        }

//        //[Obsolete( "Depreciated, use the methods for the Mobile's race", false )]
//        public static int ClipHairHue(int hue)
//        {
//            if (hue < 1102)
//                return 1102;
//            else if (hue > 1149)
//                return 1149;
//            else
//                return hue;
//        }

//        //[Obsolete( "Depreciated, use the methods for the Mobile's race", false )]
//        public static int RandomHairHue()
//        {
//            return Random(1102, 48);
//        }

//        #endregion

//        private static SkillName[] m_AllSkills = new SkillName[]
//            {
//                SkillName.Alchemy,
//                SkillName.Anatomy,
//                SkillName.AnimalLore,
//                SkillName.ItemID,
//                SkillName.ArmsLore,
//                SkillName.Parry,
//                SkillName.Begging,
//                SkillName.Blacksmith,
//                SkillName.Fletching,
//                SkillName.Peacemaking,
//                SkillName.Camping,
//                SkillName.Carpentry,
//                SkillName.Cartography,
//                SkillName.Cooking,
//                SkillName.DetectHidden,
//                SkillName.Discordance,
//                SkillName.EvalInt,
//                SkillName.Healing,
//                SkillName.Fishing,
//                SkillName.Forensics,
//                SkillName.Herding,
//                SkillName.Hiding,
//                SkillName.Provocation,
//                SkillName.Inscribe,
//                SkillName.Lockpicking,
//                SkillName.Magery,
//                SkillName.MagicResist,
//                SkillName.Tactics,
//                SkillName.Snooping,
//                SkillName.Musicianship,
//                SkillName.Poisoning,
//                SkillName.Archery,
//                SkillName.SpiritSpeak,
//                SkillName.Stealing,
//                SkillName.Tailoring,
//                SkillName.AnimalTaming,
//                SkillName.TasteID,
//                SkillName.Tinkering,
//                SkillName.Tracking,
//                SkillName.Veterinary,
//                SkillName.Swords,
//                SkillName.Macing,
//                SkillName.Fencing,
//                SkillName.Wrestling,
//                SkillName.Lumberjacking,
//                SkillName.Mining,
//                SkillName.Meditation,
//                SkillName.Stealth,
//                SkillName.RemoveTrap,
//                SkillName.Necromancy,
//                SkillName.Focus,
//                SkillName.Chivalry,
//                SkillName.Bushido,
//                SkillName.Ninjitsu,
//                SkillName.Spellweaving
//            };

//        private static SkillName[] m_CombatSkills = new SkillName[]
//            {
//                SkillName.Archery,
//                SkillName.Swords,
//                SkillName.Macing,
//                SkillName.Fencing,
//                SkillName.Wrestling
//            };

//        private static SkillName[] m_CraftSkills = new SkillName[]
//            {
//                SkillName.Alchemy,
//                SkillName.Blacksmith,
//                SkillName.Fletching,
//                SkillName.Carpentry,
//                SkillName.Cartography,
//                SkillName.Cooking,
//                SkillName.Inscribe,
//                SkillName.Tailoring,
//                SkillName.Tinkering
//            };

//        public static SkillName RandomSkill()
//        {
//            return m_AllSkills[Utility.Random(m_AllSkills.Length - (Core.ML ? 0 : Core.SE ? 1 : Core.AOS ? 3 : 6))];
//        }

//        public static SkillName RandomCombatSkill()
//        {
//            return m_CombatSkills[Utility.Random(m_CombatSkills.Length)];
//        }

//        public static SkillName RandomCraftSkill()
//        {
//            return m_CraftSkills[Utility.Random(m_CraftSkills.Length)];
//        }

//        public static void FixPoints(ref Point3D top, ref Point3D bottom)
//        {
//            if (bottom.m_X < top.m_X)
//            {
//                int swap = top.m_X;
//                top.m_X = bottom.m_X;
//                bottom.m_X = swap;
//            }

//            if (bottom.m_Y < top.m_Y)
//            {
//                int swap = top.m_Y;
//                top.m_Y = bottom.m_Y;
//                bottom.m_Y = swap;
//            }

//            if (bottom.m_Z < top.m_Z)
//            {
//                int swap = top.m_Z;
//                top.m_Z = bottom.m_Z;
//                bottom.m_Z = swap;
//            }
//        }

//        public static ArrayList BuildArrayList(IEnumerable enumerable)
//        {
//            IEnumerator e = enumerable.GetEnumerator();

//            ArrayList list = new ArrayList();

//            while (e.MoveNext())
//            {
//                list.Add(e.Current);
//            }

//            return list;
//        }

//        public static bool RangeCheck(IPoint2D p1, IPoint2D p2, int range)
//        {
//            return (p1.X >= (p2.X - range))
//                && (p1.X <= (p2.X + range))
//                && (p1.Y >= (p2.Y - range))
//                && (p2.Y <= (p2.Y + range));
//        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Output"></param>
        /// <param name="streamInput"></param>
        /// <param name="iLength"></param>
        public static void FormatBuffer( TextWriter Output, System.IO.Stream streamInput, long iLength )
        {
            Output.WriteLine( "        0  1  2  3  4  5  6  7   8  9  A  B  C  D  E  F" );
            Output.WriteLine( "       -- -- -- -- -- -- -- --  -- -- -- -- -- -- -- --" );

            long iByteIndex = 0;
            long iWhole = iLength >> 4;
            long iRem = iLength & 0xF;

            for ( long iIndex = 0; iIndex < iWhole; ++iIndex, iByteIndex += 16 )
            {
                StringBuilder strBytes = new StringBuilder( 49 );
                StringBuilder strChars = new StringBuilder( 16 );

                for ( int iIndex2 = 0; iIndex2 < 16; ++iIndex2 )
                {
                    int iByte = streamInput.ReadByte();

                    strBytes.Append( iByte.ToString( "X2" ) );

                    if ( iIndex2 != 7 )
                        strBytes.Append( ' ' );
                    else
                        strBytes.Append( "  " );

                    if ( iByte >= 0x20 && iByte < 0x80 )
                        strChars.Append( (char)iByte );
                    else
                        strChars.Append( '.' );
                }

                Output.Write( iByteIndex.ToString( "X4" ) );
                Output.Write( "   " );
                Output.Write( strBytes.ToString() );
                Output.Write( "  " );
                Output.WriteLine( strChars.ToString() );
            }

            if ( iRem != 0 )
            {
                StringBuilder strBytes = new StringBuilder( 49 );
                StringBuilder strChars = new StringBuilder( (int)iRem );

                for ( long iIndex2 = 0; iIndex2 < 16; ++iIndex2 )
                {
                    if ( iIndex2 < iRem )
                    {
                        long iByte = streamInput.ReadByte();

                        strBytes.Append( iByte.ToString( "X2" ) );

                        if ( iIndex2 != 7 )
                            strBytes.Append( ' ' );
                        else
                            strBytes.Append( "  " );

                        if ( iByte >= 0x20 && iByte < 0x80 )
                            strChars.Append( (char)iByte );
                        else
                            strChars.Append( '.' );
                    }
                    else
                        strBytes.Append( "   " );
                }

                if ( iRem < 7 )
                    strBytes.Append( ' ' );

                Output.Write( iByteIndex.ToString( "X4" ) );
                Output.Write( "   " );
                Output.Write( strBytes.ToString() );
                Output.Write( "  " );
                Output.WriteLine( strChars.ToString() );
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private static Stack<ConsoleColor> m_ConsoleColors = new Stack<ConsoleColor>();

        /// <summary>
        /// 
        /// </summary>
        /// <param name="color"></param>
        public static void PushColor(ConsoleColor color)
        {
            //try
            //{
            //    m_ConsoleColors.Push(Console.ForegroundColor);
            //    Console.ForegroundColor = color;
            //}
            //catch
            //{
            //}
        }

        /// <summary>
        /// 
        /// </summary>
        public static void PopColor()
        {
            //try
            //{
            //    Console.ForegroundColor = m_ConsoleColors.Pop();
            //}
            //catch
            //{
            //}
        }

//        public static bool NumberBetween(double num, int bound1, int bound2, double allowance)
//        {
//            if (bound1 > bound2)
//            {
//                int i = bound1;
//                bound1 = bound2;
//                bound2 = i;
//            }

//            return (num < bound2 + allowance && num > bound1 - allowance);
//        }

//        public static void AssignRandomHair(Mobile m)
//        {
//            AssignRandomHair(m, true);
//        }
//        public static void AssignRandomHair(Mobile m, int hue)
//        {
//            m.HairItemID = m.Race.RandomHair(m);
//            m.HairHue = hue;
//        }
//        public static void AssignRandomHair(Mobile m, bool randomHue)
//        {
//            m.HairItemID = m.Race.RandomHair(m);

//            if (randomHue)
//                m.HairHue = m.Race.RandomHairHue();
//        }

//        public static void AssignRandomFacialHair(Mobile m)
//        {
//            AssignRandomFacialHair(m, true);
//        }
//        public static void AssignRandomFacialHair(Mobile m, int hue)
//        {
//            m.FacialHairHue = m.Race.RandomFacialHair(m);
//            m.FacialHairHue = hue;
//        }
//        public static void AssignRandomFacialHair(Mobile m, bool randomHue)
//        {
//            m.FacialHairItemID = m.Race.RandomFacialHair(m);

//            if (randomHue)
//                m.FacialHairHue = m.Race.RandomHairHue();
//        }

//        public static List<TOutput> CastConvertList<TInput, TOutput>(List<TInput> list) where TOutput : TInput
//        {
//            return list.ConvertAll<TOutput>(new Converter<TInput, TOutput>(delegate(TInput value) { return (TOutput)value; }));
//        }

//        public static List<TOutput> SafeConvertList<TInput, TOutput>(List<TInput> list) where TOutput : class
//        {
//            List<TOutput> output = new List<TOutput>(list.Capacity);

//            for (int i = 0; i < list.Count; i++)
//            {
//                TOutput t = list[i] as TOutput;

//                if (t != null)
//                    output.Add(t);
//            }

//            return output;
        //        }

        #region ILock
        /// <summary>
        /// 开始锁定对象以实现内部的操作, 只锁定具有ILock接口的类
        /// </summary>
        /// <param name="lockObject">需要锁定的对象</param>
        /// <returns>返回是否锁定成功</returns>
        public static bool Lock( ILock lockObject )
        {
            if ( lockObject == null )
                return false;

            return lockObject.Lock();
        }

        /// <summary>
        /// 检测该对象是否是可以锁定的对象
        /// </summary>
        /// <param name="isAllowLockObject">需检测的锁定对象</param>
        /// <returns>返回该对象是否是可以锁定的对象</returns>
        public static bool IsAllowLockObject( object isAllowLockObject )
        {
            ILock l_ILock = isAllowLockObject as ILock;
            if ( l_ILock == null )
                return false;
            else
                return true;
        }

        /// <summary>
        /// 释放已经锁定的对象, 只释放具有ILock接口的类
        /// </summary>
        /// <param name="freeObject">需要释放锁定的对象</param>
        public static void Free( ILock freeObject )
        {
            if ( freeObject != null )
                freeObject.Free();
        }
        #endregion

        #region Convert FLOAT UINT INT
        /// <summary>
        /// 
        /// </summary>
        /// <param name="fValue"></param>
        /// <returns></returns>
        public static uint FloatToUint( float fValue )
        {
            CONVERT_FLOAT_INT_UINT l_ConvertFloat = new CONVERT_FLOAT_INT_UINT();
            l_ConvertFloat.fFloat = fValue;

            return l_ConvertFloat.uiUint;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="uiValue"></param>
        /// <returns></returns>
        public static float UintToFloat( uint uiValue )
        {
            CONVERT_FLOAT_INT_UINT l_ConvertFloat = new CONVERT_FLOAT_INT_UINT();
            l_ConvertFloat.uiUint = uiValue;

            return l_ConvertFloat.fFloat;
        }
        #endregion
    }

    //public class Utility
    //{
    //    #region zh-CHS 私有成员变量 | en Private Member Variables
    //    private static Encoding         m_UTF8;
    //    private static Encoding         m_UTF8WithEncoding;

    //    private static int              s_Seed = 1;
    //    private static RandomList       s_RandomList = new RandomList();
    //    //脚本编译后的程序集
    //    private static Assembly         s_ExternAsm = null;
    //    //程序集的全部构造函数信息列表
    //    private static Hashtable        s_AllConstructors = new Hashtable();
    //    #endregion

    //    #region zh-CHS 属性 | en Properties
    //    public static Assembly ExternAsm
    //    {
    //        get { return s_ExternAsm; }
    //    }

    //    public static Util.RandomList RandomList
    //    {
    //        get { return s_RandomList; }
    //    }

    //    public static Hashtable AllConstructors
    //    {
    //        get { return s_AllConstructors; }
    //    }
    //    #endregion

    //    #region zh-CHS 公开的函数 | en Class Public Methods
    //    public static bool ToBoolean(string value)
    //    {
    //        bool l_bFlag;
    //        try
    //        {
    //            l_bFlag = Convert.ToBoolean(value);
    //        }
    //        catch
    //        {
    //            l_bFlag = false;
    //        }
    //        return l_bFlag;
    //    }

    //    public static double ToDouble(string value)
    //    {
    //        double l_Num;
    //        try
    //        {
    //            l_Num = Convert.ToDouble(value);
    //        }
    //        catch
    //        {
    //            l_Num = 0;
    //        }
    //        return l_Num;
    //    }

    //    public static TimeSpan ToTimeSpan(string value)
    //    {
    //        TimeSpan l_Span;
    //        try
    //        {
    //            l_Span = TimeSpan.Parse(value);
    //        }
    //        catch
    //        {
    //            l_Span = TimeSpan.Zero;
    //        }
    //        return l_Span;
    //    }

    //    public static int ToInt32(string value)
    //    {
    //        int l_Num;
    //        try
    //        {
    //            if (value.StartsWith("0x"))
    //                return Convert.ToInt32(value.Substring(2), 0x10);
    //            else
    //                l_Num = Convert.ToInt32(value);
    //        }
    //        catch
    //        {
    //            l_Num = 0;
    //        }
    //        return l_Num;
    //    }

    //    //获取类的名字，去掉前面的指示域
    //    public static string ClassName(object value)
    //    {
    //        string l_Text = value.GetType().ToString();
    //        char[] l_chArray1 = new char[1] { '.' };
    //        string[] l_TextArray = l_Text.Split(l_chArray1);
    //        return l_TextArray[l_TextArray.Length - 1];
    //    }

    //    //获取类的名字，去掉前面的指示域
    //    public static string ClassName(string value)
    //    {
    //        char[] l_chArray1 = new char[1] { '.' };
    //        string[] l_TextArray = value.Split(l_chArray1);
    //        return l_TextArray[l_TextArray.Length - 1];
    //    }


    //    //在程序集中寻找全部的构造函数并填充在列表中
    //    public static void FillConstructorList(Assembly value)
    //    {
    //        if (value == null) return;
    //        else s_ExternAsm = value;

    //        ConstructorInfo[] l_InfoArray;
    //        Module[] l_ModuleArray = s_ExternAsm.GetModules(false);
    //        Module l_Module = l_ModuleArray[0];
    //        Type[] l_TypeArray = l_Module.FindTypes(Module.FilterTypeName, "*");

    //        int l_Num1 = 0;
    //        int l_Num2 = 0;
    //        for (l_Num1 = 0; l_Num1 < l_TypeArray.Length; l_Num1++)
    //        {
    //            Type l_Type = l_TypeArray[l_Num1];
    //            if (!l_Type.Name.StartsWith("$$"))
    //            {
    //                l_InfoArray = l_Type.GetConstructors();
    //                for (l_Num2 = 0; l_Num2 < l_InfoArray.Length; l_Num2++)
    //                {
    //                    ConstructorInfo l_Info = l_InfoArray[l_Num2];
    //                    ParameterInfo[] infoArray = l_Info.GetParameters();
    //                    if (infoArray.Length == 0)
    //                    {
    //                        s_AllConstructors[ClassName(l_Type.Name)] = l_Info;
    //                        break;
    //                    }
    //                }
    //            }
    //        }

    //        l_ModuleArray = Assembly.GetAssembly(typeof(Utility)).GetModules(false);
    //        l_Module = l_ModuleArray[0];
    //        l_TypeArray = l_Module.FindTypes(Module.FilterTypeName, "*");
    //        for (l_Num1 = 0; l_Num1 < l_TypeArray.Length; l_Num1++)
    //        {
    //            Type l_Type = l_TypeArray[l_Num1];
    //            if (!l_Type.Name.StartsWith("$$"))
    //            {
    //                l_InfoArray = l_Type.GetConstructors();
    //                for (l_Num2 = 0; l_Num2 < l_InfoArray.Length; l_Num2++)
    //                {
    //                    ConstructorInfo l_Info = l_InfoArray[l_Num2];
    //                    ParameterInfo[] infoArray = l_Info.GetParameters();
    //                    if (infoArray.Length == 0)
    //                    {
    //                        s_AllConstructors[ClassName(l_Type.Name)] = l_Info;
    //                        break;
    //                    }
    //                }
    //            }
    //        }
    //    }

    //    public static ConstructorInfo FindConstructor(string value)
    //    {
    //        return (ConstructorInfo)s_AllConstructors[ClassName(value)];
    //    }

    //    public static ConstructorInfo FindConstructor(string value, Assembly fromAssembly)
    //    {
    //        return (ConstructorInfo)s_AllConstructors[ClassName(value)];
    //    }

    //    public static double RandomDouble()
    //    {
    //        int num1 = s_RandomList.RandomListValue[s_Seed++ & 0xfffff] & 0xfffffff;
    //        int num2 = s_RandomList.RandomListValue[s_Seed++ & 0xfffff] & 0xfffffff;
    //        double num3 = ((double)num1) / 72057594037927936;
    //        return (num3 + (((double)num2) / 268435456));
    //    }

    //    public static int Random(int max)
    //    {
    //        return (s_RandomList.RandomListValue[s_Seed++ & 0xfffff] % max);
    //    }

    //    public static int Random(int iMin, int iMax)
    //    {
    //        if (iMin == iMax)
    //            return iMin;

    //        return (iMin + (s_RandomList.RandomListValue[s_Seed++ & 0xfffff] % (iMax - iMin)));
    //    }

    //    public static int Random4()
    //    {
    //        return (s_RandomList.RandomListValue[s_Seed++ & 0xfffff] & 3);
    //    }

    //    public static int Random8()
    //    {
    //        return (s_RandomList.RandomListValue[s_Seed++ & 0xfffff] & 7);
    //    }

    //    public static int Random16()
    //    {
    //        return (s_RandomList.RandomListValue[s_Seed++ & 0xfffff] & 15);
    //    }

    //    public static int Random1024()
    //    {
    //        return (s_RandomList.RandomListValue[s_Seed++ & 0xfffff] & 0x3ff);
    //    }

    //    public static int Random1024x1024()
    //    {
    //        return (s_RandomList.RandomListValue[s_Seed++ & 0xfffff] & 0xfffff);
    //    }

    //    // Properties
    //    public static Encoding UTF8
    //    {
    //        get
    //        {
    //            if (m_UTF8 == null)
    //                m_UTF8 = new UTF8Encoding(false, false);
    //            return m_UTF8;
    //        }
    //    }

    //    public static Encoding UTF8WithEncoding
    //    {
    //        get
    //        {
    //            if (m_UTF8WithEncoding == null)
    //                m_UTF8WithEncoding = new UTF8Encoding(true, false);
    //            return m_UTF8WithEncoding;
    //        }
    //    }
    //    #endregion
    //}
}
#endregion

